package com.frxuexi.park2210.notice

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.frxuexi.lib_base.entity.NoticeBean
import com.frxuexi.lib_base.entity.NoticeBeanItem
import com.frxuexi.lib_base.net.ApiService
import com.google.gson.Gson
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.Exception

class NewsDataSource(val apiService: ApiService):PagingSource<Int,NoticeBeanItem>() {
    override fun getRefreshKey(state: PagingState<Int, NoticeBeanItem>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, NoticeBeanItem> {
        return  try {
            val page=params.key?:0
            val map = mapOf<String, Int>("page" to page)
            val json = Gson().toJson(map)
            val body = RequestBody.create("application/json".toMediaTypeOrNull(), json)
            val notices = apiService.getNotices(body)
            val noticeBean=Gson().fromJson(notices.values,NoticeBean::class.java)
            val nextPage=if(noticeBean!=null) page+1 else null
            LoadResult.Page(noticeBean,null,nextPage)
        }catch (e:Exception){
            LoadResult.Error(e)
        }
    }
}